package com.xh.bussiness.xkw.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class Pic2Base64Utils {
    static Logger logger = LoggerFactory.getLogger(Pic2Base64Utils.class);

    static String prefix_img = "data:image/jpg;base64,";

    public static String Pic2EncodeStr(String filePath,boolean containsPrefix){

        long start = System.currentTimeMillis();
        try (InputStream in = new FileInputStream(new File(filePath))) {
            byte[] data = new byte[in.available()];
            in.read(data);
            BASE64Encoder encoder = new BASE64Encoder();
            String encode = encoder.encode(data);
            long end = System.currentTimeMillis();
            logger.info("------------------------图片转base64完成，用时：" + (end - start) + "ms--------------------------");
            if(containsPrefix){
                return prefix_img + encode;
            }else{
                return encode;
            }
        } catch (Exception e) {
            logger.error("----------------------图片转base64失败,异常信息:" + e.getMessage() + "--------------------------");
        }

        return null;
    }

    public static void main(String[] args) {
        String filePath = "/home/thev/图片/2021-01-27_10-44.png";

        String perfixe = "data:image/jpg;base64,";
        System.out.println(perfixe+ Pic2Base64Utils.Pic2EncodeStr(filePath,false));
    }
}
